let isEditMode = false;
var userid
$.ajax({
    url:"/user/findByName",
    type:"POST",
    async:false,
    data: {
        username:$.cookie("username")
    },
    success:function (res){
        $("#realName").val(res.data.realname);
        $("#gender").val(res.data.gender)
        $("#phone").val(res.data.phone)
        $("#age").val(res.data.age)
        $("#email").val(res.data.email)
        $("#idCard").val(res.data.idCard)
        $("#bio").val(res.data.description)
        $(".avatar img").attr("src", res.data.icon)
        $("#currentPassword").val(res.data.password)
        $("#username").val(res.data.account)
        userid = res.data.id
        console.log(userid)
    }
})
// 切换编辑模式
function toggleEditMode() {
    isEditMode = !isEditMode;
    const formControls = document.querySelectorAll('#personalInfoForm .form-control:not([id="idCard"]):not([id="username"])');
    const genderSelect = document.getElementById('gender');
    const editBtn = document.getElementById('editBtn');
    const saveBtn = document.getElementById('saveBtn');

    if (isEditMode) {
        // 进入编辑模式
        formControls.forEach(control => {
            control.readOnly = false;
            control.style.backgroundColor = 'white';
        });
        genderSelect.disabled = false;
        editBtn.style.display = 'none';
        saveBtn.style.display = 'flex';
    } else {
        // 退出编辑模式
        formControls.forEach(control => {
            control.readOnly = true;
            control.style.backgroundColor = '#f8f9fa';
        });
        genderSelect.disabled = true;
        editBtn.style.display = 'flex';
        saveBtn.style.display = 'none';
    }
}

// 保存信息
function saveInfo() {
    const form = document.getElementById('personalInfoForm');
    const formData = new FormData(form);
    formData.append("id", userid)
    console.log(JSON.stringify(formData))

    // 这里可以添加表单验证
    if (!validateForm()) {
        return;
    }
    // 模拟保存操作
    $.ajax({
        url:"/user/updateUser",
        type:"POST",
        data: {
            id:userid,
            realname:formData.get("realName"),
            gender:formData.get("gender"),
            phone:formData.get("phone"),
            age:formData.get("age"),
            email:formData.get("email"),
            description:formData.get("description"),
            icon:$(".avatar img").attr("src"),
            account:formData.get("username"),
        },
        success:function (res){
            console.log(res)
        }
    })

    // 显示成功消息
    alert('个人信息保存成功！');

    // 退出编辑模式
    toggleEditMode();
}

// 表单验证
function validateForm() {
    const phone = document.getElementById('phone').value;
    const email = document.getElementById('email').value;

    // 简单的手机号验证
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phone)) {
        alert('请输入有效的手机号码');
        return false;
    }

    // 简单的邮箱验证
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
        alert('请输入有效的邮箱地址');
        return false;
    }

    return true;
}

// 修改密码
function changePassword() {
    const currentPassword = document.getElementById('currentPassword').value;
    const newPassword = document.getElementById('newPassword').value;
    const confirmPassword = document.getElementById('confirmPassword').value;

    if (!currentPassword || !newPassword || !confirmPassword) {
        alert('请填写所有密码字段');
        return;
    }

    if (newPassword !== confirmPassword) {
        alert('新密码和确认密码不一致');
        return;
    }

    if (newPassword.length < 8) {
        alert('密码长度至少8位');
        return;
    }
    $.ajax({
        url:"/user/updatePassword",
        type:"POST",
        data: {
            account:$("#username").val(),
            password:currentPassword,
            newPassword:newPassword,
        },
        success:function (res){
            console.log(res)
        }
    })
    // 模拟密码修改
    console.log('修改密码:', { currentPassword, newPassword });
    alert('密码修改成功！');

    // 清空密码字段
    document.getElementById('currentPassword').value = '';
    document.getElementById('newPassword').value = '';
    document.getElementById('confirmPassword').value = '';
}

// 切换密码显示/隐藏
function togglePassword(inputId) {
    const input = document.getElementById(inputId);
    const toggleBtn = input.nextElementSibling;
    const icon = toggleBtn.querySelector('i');

    if (input.type === 'password') {
        input.type = 'text';
        icon.className = 'bi bi-eye-slash';
    } else {
        input.type = 'password';
        icon.className = 'bi bi-eye';
    }
}

// 处理头像上传
function handleAvatarUpload(event) {
    const file = event.target.files[0];
    if (file) {
        if (!file.type.startsWith('image/')) {
            alert('请选择图片文件');
            return;
        }

        const reader = new FileReader();
        reader.onload = function(e) {
            document.querySelector('.avatar img').src = e.target.result;
        };
        reader.readAsDataURL(file);

        // 这里可以添加上传到服务器的代码
        console.log('上传头像:', file.name);
        const formData = new FormData();
        console.log("file是什么: ", file);
        formData.append("file", file);  // "file" 必须和后端参数名一致

        $.ajax({
            url: "/upload",  // 替换为你的Servlet URL
            type: "POST",
            data: formData,
            processData: false,      // 禁止jQuery处理数据（文件上传必须）
            contentType: false,      // 禁止设置Content-Type（浏览器自动生成multipart/form-data）
            cache: false,            // 禁用缓存
            success: function (response) {
                $(".avatar img").attr("src", response.data)
            }
        })
    }
}

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    // 底部导航交互
    const navItems = document.querySelectorAll('.nav-item');
    navItems.forEach(item => {
        item.addEventListener('click', function() {
            navItems.forEach(nav => nav.classList.remove('active'));
            this.classList.add('active');
        });
    });
});